package som.simon.reactor;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

public class MonoMain {

    public static void main(String[] args) throws InterruptedException, RuntimeException {

        // monoTest();
        // fluxEmptyTest();

        Flux<Integer> nums = Flux.range(1, 10)
                .filter(i -> i != 2)
                // 延迟一秒
                .delayElements(Duration.ofSeconds(1))
                // 被忽略  filter 会触发
                .doOnDiscard(Integer.class, o -> {
                    System.out.println("doOnDiscard... item: " + o);
                })
                // 完成
                .doOnComplete(() -> {
                    System.out.println("doOnComplete...");
                })
                // 取消后
                .doOnCancel(() -> {
                    System.out.println("doOnCancel...");
                })
                // 下一个
                .doOnNext(o -> {
                    System.out.println("doOnNext... item: " + o);
                })
                .doOnRequest(ix -> {
                    System.out.println("doOnRequest... ix: " + ix);
                })
                // 变量每一个
                .doOnEach(o -> {
                    Integer i = o.get();
                    if (i != null && i == 4) {
                        throw new RuntimeException("模拟错误！");
                    }
                    System.out.println("doOnEach... item: " + o);

                })

                // 错误
                .doOnError(throwable -> {
                    System.out.println("doOnError... throwable: " + throwable.getMessage());
                });

        // 只有调用才会出发事件
        nums.subscribe(ix -> {
            System.out.println();
        });

        Thread.sleep(5000);
    }

    private static void fluxEmptyTest() {
        // 事件感知  doOnComplete
        Flux<Object> empty = Flux.empty()
                .doOnComplete(() -> {
                    System.out.println("流结束了");
                })
                .doOnCancel(() -> {

                })
                .doOnError(err -> {

                })
                .doOnNext(o -> {

                });

        // 只有调用才会出发事件
        empty.subscribe();
    }

    private static void monoTest() {
        Mono<Integer> just = Mono.just(1);
        just.subscribe(System.out::println);
    }

}
